<template>
  <div class="group-info-page">
    <!-- 页面标题 -->
    <van-nav-bar
      title="群信息"
      left-text="返回"
      left-arrow
      @click-left="forwardRoute"
    />

    <!-- 群基本信息 -->
    <div class="group-header">
      <van-image
        round
        width="60px"
        height="60px"
        :src="groupAvatar"
        class="group-avatar"
      />
      <div class="group-meta">
        <h3 class="group-name">{{ groupName }}</h3>
        <p class="group-member-count">共 {{ memberList.length }} 人</p>
      </div>
    </div>

    <!-- 群成员列表 -->
    <van-cell-group title="群成员" class="member-list">
      <div class="members-grid">
        <div
          v-for="member in memberList"
          :key="member.memberId"
          class="member-item"
        >
          <van-image
            round
            width="40px"
            height="40px"
            :src="member.avatar"
          />
          <span class="member-name">{{ member.realname || '未知用户' }}</span>
        </div>
        <!-- 添加成员按钮（放在最后） -->
        <div
        class="member-item"
        @click="addMember"
        >
        <div class="add-member-btn">
            <van-icon name="plus" size="24" color="#969799" />
        </div>
        <span class="member-name">邀请</span>
        </div>
      </div>
    </van-cell-group>

    <!-- 退出群聊按钮 -->
    <div class="exit-section">
      <van-button
        type="danger"
        block
        @click="exitGroup"
      >
        退出群聊
      </van-button>
    </div>
  </div>
</template>

<script>
import { postAction, getFileAccessHttpUrl } from "@/api";
import { Dialog, Toast } from 'vant';
export default {
  name: 'GroupInfoPage',
  data() {
    return {
        userInfo:{},
        groupId: '',
      groupName: '', // 可从路由或接口获取
      groupAvatar: '', // 可动态设置
      memberList: [] // 群成员列表
    };
  },
  async created() {
    const userInfoString = localStorage.getItem("pro__login_user_info");
    if (userInfoString) {
      const userInfo = JSON.parse(userInfoString);
      this.userInfo = userInfo.value;
    }
    this.groupId = this.$route.params.groupId;
    this.groupName = this.$route.params.navTitle;
    await this.fetchGroupMembers();
  },
  methods: {
    forwardRoute(){
        this.$router.push(`/coordination/chat/${this.groupId}`)
    },
    // 添加成员
  addMember() {
    // 方案1：跳转到添加成员页面
    this.$router.push({
      name: 'addGroupMember', // 假设你有一个添加成员页面
      params: {
        groupId: this.groupId,
        navTitle: this.groupName
      }
    });

    // 方案2：弹出对话框选择联系人（适合在当前页操作）
    // this.showAddMemberDialog = true;
  },
    // 模拟调用接口获取成员
    async fetchGroupMembers() {
        const that = this;
      postAction("/sys/chat/member/getGroupMember/",{
        groupId: this.groupId
      }).then(res => {
        this.memberList = res.result;
        this.memberList.forEach((item) => {
            item.avatar = item.avatar ? getFileAccessHttpUrl(item.avatar) : '/static/mobile/img/common/user_default.webp';
          });
        console.log("🚀 ~ :86 ~ fetchGroupMembers ~ this.memberList:", this.memberList)
      })

      postAction('/sys/chat/relative', {
            type: "meeting",
            userId: this.userInfo.id,
        }).then((res) => {
            res.result.forEach(function (item) { 
                if(item.goalId == that.groupId){
                    that.groupAvatar = item.avatar ? getFileAccessHttpUrl(item.avatar) : '/static/mobile/img/common/user_default.webp'
                    console.log("🚀 ~ :129 ~ fetchGroupMembers ~ this.groupAvatar:", that.groupAvatar)
                }
            });
        })

    },

    //退出群聊
    exitGroup() {
      const that = this;
      const currentUser = this.memberList.find(g => g.memberId == this.userInfo.id);
      console.log("🚀 ~ :101 ~ exitGroup ~ this.memberList:", this.memberList)
      console.log("🚀 ~ :101 ~ exitGroup ~ this.userInfo.id:", this.userInfo.id)

      if (!currentUser) {
        Toast.fail('未找到当前用户信息');
        return;
      }

      console.log('当前用户信息:', currentUser);

      // 第一层：确认是否退群
      Dialog.confirm({
        title: '确定退群吗？',
        message: '退群后将收不到该群消息',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          // 用户点击“确定”
          if (currentUser.role === 1) {
            // 是群主：二次确认，退群即解散群
            Dialog.confirm({
              title: '确定继续退群吗？',
              message: '您是群主，退群后群将解散，所有成员将收不到消息',
              confirmButtonText: '确定',
              cancelButtonText: '取消',
            })
              .then(() => {
                // 群主确认退群
                that.handleExitGroup(true);
              })
              .catch(() => {
                // 群主取消
                Toast('已取消退群');
              });
          } else {
            // 普通成员，直接退群
            that.handleExitGroup(false);
          }
        })
        .catch(() => {
          // 用户取消退群
          Toast('已取消');
        });
    },

    // 封装退群请求
    handleExitGroup(isGroupLeader) {
      const params = {
        groupId: this.groupId,
        memberIds: this.userInfo.id,
        isGroupLeader: isGroupLeader
      };

      // 假设 postAction 是你封装的请求方法
      postAction("/sys/chat/member/deleteGroupMember", params)
        .then(res => {
          if (res.success) {
            Toast.success('已退出群聊');
            // 退出后返回上一页
            this.$router.push({ name: "chat" });
          } else {
            Toast.fail(res.message || '退群失败');
          }
        })
        .catch(err => {
          Toast.fail('网络错误，退群失败');
          console.error(err);
        });
    }
  }
};
</script>

<style scoped>
.group-info-page {
  background: #f7f8fa;
  min-height: 100vh;
}

.group-header {
  display: flex;
  align-items: center;
  padding: 16px;
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
}

.group-avatar {
  margin-right: 12px;
}

.group-meta {
  flex: 1;
}

.group-name {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #323233;
}

.group-member-count {
  margin: 4px 0 0;
  font-size: 12px;
  color: #969799;
}

.member-list {
  margin-top: 10px;
}

.members-grid {
  display: flex;
  flex-wrap: wrap;
  padding: 10px;
  background: #fff;
}

.member-item {
  width: 20%;
  text-align: center;
  margin-bottom: 10px;
  display: flex; /* 使用 Flexbox 布局 */
  flex-direction: column; /* 竖直排列子元素 */
  align-items: center; /* 水平居中 */
  justify-content: center; /* 垂直居中 */
  height: 60px; /* 设置固定高度 */
}

.member-item img {
  margin: 0 auto;
}

.member-name {
  display: block;
  font-size: 12px;
  color: #323233;
  margin-top: 4px;
  word-break: keep-all;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.exit-section {
  margin: 20px 16px;
}
/* 添加成员按钮 */
.add-member-btn {
  width: 40px;
  height: 40px;
  border: 1px dashed #dcdee0;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f7f8fa;
  box-sizing: border-box;
}
</style>